package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/19  14:29
 * @description：TODO 登录
 */
@RestController
@RequestMapping("/api/user/passport")
public class LoginApiController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo) {
        if (null != userInfo) {
            //1.校验用户名不能为空
            if (StringUtils.isEmpty(userInfo.getLoginName())) {
                return Result.fail().message("用户名不能为空");
            }
            //2.校验密码不能为空
            if (StringUtils.isEmpty(userInfo.getPasswd())) {
                return Result.fail().message("密码不能为空");
            }
        } else {
            return Result.fail().message("用户信息不能为空");
        }
        //校验用户名及密码是否正确
        //将用户的昵称返回到页面上进行回显
        userInfo = userInfoService.login(userInfo);
        //  用户微服务
        //  1、校验用户密码是否正确
        if (null != userInfo) {
            // 2、颁发令牌  返回用户昵称
            String token = UUID.randomUUID().toString().replace("-", "");
            String nickName = userInfo.getNickName();
            Map map = new HashMap();
            map.put("token", token);
            map.put("nickName", nickName);

            // 3、保存用户信息到Redis
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,userInfo.getId().toString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);//response.data.data.token=result.map.token
        } else {
            return Result.fail().message("用户名或密码不正确");
        }
    }
    //退出
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("token");
        System.out.println(token);
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+token);
        return Result.ok();
    }


}
